import { hasPayServiceApi } from '@/api/Plan';
import { useAppSelector } from '@/redux/store';
import { DownOutlined } from '@ant-design/icons';
import type { ButtonProps } from 'antd';
import { App, Button, message } from 'antd';
import { useEffect, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import CourseWareDetail from '../resourceLibraryComp/CourseWareDetail';
import ResourceNameForTable from '../resourceLibraryComp/ResourceNameForTable';
import TestPaperDetail from '../resourceLibraryComp/TestPaperDetail';

interface CourseListItemProps {
  name?: string;
  type?: string;
  resourceType?: string;
  isCharge?: number;
  /**
   * @desc 课件的guid
   */
  guid?: string;
  /**
   * @desc 是否有删除按钮  课件包里的课件不能删
   */
  canDel?: boolean;
  onDelete?: ButtonProps['onClick'];
  /**
   * @desc 是否展开详情,可能用不到
   */
  show?: boolean;
  /**
   * @desc 详情展开收起时候的回掉函数
   */
  onShow?(show: boolean): void;
}

function CourseListItem({
  name,
  type,
  resourceType,
  guid,
  isCharge,
  canDel,
  onDelete,
  show,
  onShow,
}: CourseListItemProps) {
  const navigator = useNavigate();
  const {
    modal: { confirm },
  } = App.useApp();
  const { loginRole } = useAppSelector((state) => state.loginUser);
  const { entId, organizationType } = useAppSelector((state) => state.loginEnt); //organizationType 1:协会，0：企业
  const [hasPayService, SetHasPayService] = useState<boolean>(true);

  useEffect(() => {
    if (isCharge && organizationType === 0) {
      if (entId && isCharge) {
        //当前企业是否购买学习位
        hasPayServiceApi({ entId })
          .then((res) => {
            if (res.code === '200') {
              SetHasPayService(!!res.data);
            }
          })
          .catch((err) => {
            console.log('--TestPaperDetail--hasPayServiceApi--err--:', err);
          });
      }
    }
  }, [isCharge, entId, organizationType]);
  // 0不渲染dom,1渲染但不显示,2显示
  const [_showDetail, setShowDetail] = useState<number>(0);
  const showDetail = useMemo(() => {
    if (typeof show === 'boolean') {
      return show ? 2 : _showDetail === 0 ? 0 : 1;
    } else {
      return _showDetail;
    }
  }, [show, _showDetail]);
  const showDetailToggle = () => {
    if (showDetail !== 2) {
      if (hasPayService) {
        setShowDetail(2);
        onShow?.(true);
      } else {
        confirm({
          title: '提示',
          content: '企业还未购买安学行学习位，无法查看收费内容，请前往购买安学行学习位！',
          centered: true,
          onOk: () => {
            if (loginRole == '1' || loginRole == '0') {
              navigator('/safeService/buyService');
            } else {
              message.warning('您暂无权限，请联系企业管理人员！');
            }
          },
        });
      }
    } else {
      setShowDetail(1);
      onShow?.(false);
    }
  };

  const text = showDetail === 2 ? '收起' : '展开';

  const coursewareNode = useMemo(() => {
    if (guid) {
      if (type === '视频课件') {
        return (
          <CourseWareDetail
            coursewareId={guid}
            noStyle
            resourceType={resourceType}
            isCharge={isCharge || 0}
            hasPayService={hasPayService}
          />
        );
      } else if (type === 'pdf课件') {
        return (
          <CourseWareDetail
            coursewareId={guid}
            noStyle
            resourceType={resourceType}
            isCharge={isCharge || 0}
            hasPayService={hasPayService}
          />
        );
      } else if (type === '图文课件') {
        return (
          <CourseWareDetail
            coursewareId={guid}
            noStyle
            resourceType={resourceType}
            isCharge={isCharge || 0}
            hasPayService={hasPayService}
          />
        );
      } else if (type === '试卷') {
        return (
          <TestPaperDetail
            coursewareId={guid}
            resourceType={resourceType}
            isCharge={isCharge || 0}
            hasPayService={hasPayService}
          />
        );
      } else {
        return <>开发中...</>;
      }
    }
    return null;
  }, [type, guid]);

  const resourceFrom = useMemo(() => {
    if (type === '视频课件') {
      return 'videoCourseWare';
    } else if (type === 'pdf课件') {
      return 'pdfCourseWare';
    } else if (type === '图文课件') {
      return 'graphicCourseWare';
    } else if (type === '试卷') {
      return 'testPaper';
    } else {
      return 'testPaper';
    }
  }, [type]);

  if (type && name && guid) {
    return (
      <>
        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
            gap: 8,
          }}
        >
          <div style={{ flexGrow: 1 }}>
            <ResourceNameForTable title={name} resourceType={0} resourceFrom={resourceFrom} canPointer={true} />
          </div>
          <div style={{ flexShrink: 0 }}>{type}</div>

          <div style={{ flexShrink: 0 }}>
            <Button size="small" type="text" onClick={showDetailToggle} style={{ color: '#3E84E9' }}>
              {text}
              <DownOutlined rotate={showDetail === 2 ? 180 : 0} />
            </Button>
            {/* <DragOutlined style={{ cursor: 'move' }} /> */}
            {onDelete && canDel ? (
              <Button type="text" danger size="small" onClick={onDelete}>
                删除
              </Button>
            ) : null}
          </div>
        </div>
        {showDetail ? (
          <div
            hidden={showDetail === 1}
            style={{
              background: '#F0F2F5',
              padding: 16,
              paddingBottom: 8,
              borderRadius: 4,
              marginTop: 8,
              marginBottom: 8,
            }}
          >
            {coursewareNode}
            <div style={{ textAlign: 'center' }}>
              <Button size="small" type="text" onClick={showDetailToggle}>
                点击收起
                <DownOutlined rotate={180} />
              </Button>
            </div>
          </div>
        ) : null}
      </>
    );
  } else {
    return <></>;
  }
}

export { CourseListItem };
export type { CourseListItemProps };
